package com.tcu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tcu.base.utils.MD5Util;
import com.tcu.base.utils.SaltUtil;
import com.tcu.exception.SmartException;
import com.tcu.user.entity.User;
import com.tcu.user.entity.vo.UserVo;
import com.tcu.user.mapper.RoleMapper;
import com.tcu.user.mapper.UserMapper;
import com.tcu.user.service.IUserService;
import org.mockito.internal.matchers.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private RoleMapper roleMapper;

    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }

    @Override
    public User register(User user) {
/** 1,注册的时候，不能有id
 *  2,判断用户名是否存在，如果存在，不能注册
 *  3，生成salt
 *  4，生成密码
 *  5，插入数据库
  */
        if(user.getId()!=null){
            throw new SmartException(20001,"注册的时候，id不能为空");
        }
        if (isRepeatName(user.getUsername())) {
            throw new SmartException(20001,"用户名已存在");
        }
        String salt = SaltUtil.generateSalt(4);
        user.setSalt(salt);
        String newPass = MD5Util.toMD5(user.getPassword(), salt);
        user.setPassword(newPass);
        baseMapper.insert(user);
        user.setPassword(null);
        return user;
    }

    @Override
    public Boolean isRepeatName(String username) {
        User byName = baseMapper.findByName(username);
        if(byName==null){
            return false;
        }
        return true;
    }

    @Override
    public IPage<User> pageListCondition(Long page, Long size, UserVo userVo) {
        IPage<User> iPage = new Page<>(page,size);

        NotNull notNull = NotNull.NOT_NULL;
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like(notNull.matches(userVo.getUsernameLike()),"username",userVo.getUsernameLike())
                .like(notNull.matches(userVo.getEmailLike()),"email",userVo.getEmailLike())
                .like(notNull.matches(userVo.getTelephoneLike()),"telephone",userVo.getTelephoneLike());
        baseMapper.selectPage(iPage,wrapper);
        return iPage;
    }

    @Override
    @Transactional
    public Boolean updateUserRoles(String userId, List<String> roles) {
        roleMapper.deleteRoleIdsByUid(userId);
        roles.forEach(roleId->{
            roleMapper.addRoleForUser(userId,roleId);
        });
        return true;
    }
}
